package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("consumer")
//@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        return userClient.queryById(id);
    }

    /*
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "defaultFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
    })
    @GetMapping("{id}")
    public String queryById(@PathVariable("id") Long id){
        if(id == 1){
            throw new RuntimeException("我是故意的！");
        }
        String url =  "http://user-service/user/" + id;
        return restTemplate.getForObject(url, String.class);
    }

    public String defaultFallback(Long id){
        return "别挤了，服务器快炸了！";
    }*/

    /*
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        // 根据serviceId拉取服务的实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 负载均衡算法，选出一个实例
        int num = new Random().nextInt(instances.size());
        ServiceInstance instance = instances.get(num);
        // 获取实例的host和port
        String host = instance.getHost();
        int port = instance.getPort();
        String url =  String.format("http://%s:%d/user/%d", host, port, id);

        User user = restTemplate.getForObject(url, User.class);
        return user;
    }*/
}
